/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/
#pragma once

#include <unordered_map>
#include <stdint.h>

#ifdef _DEBUG
#ifdef _MSC_VER
#define PERF_QUERY kPerformance _perf_query_(_T(__FUNCSIG__) _T("()"))
#define PERF_SUBQUERY(x) kPerformance _perf_query_(_T(__FUNCSIG__) _T("() ") _T(x))
#else
#define PERF_XSTR(s) PERF_STR(s)
#define PERF_STR(s) _T(#s)
#define PERF_QUERY kPerformance _perf_query_(_T(__FILE__) _T(":") PERF_XSTR(__LINE__) _T(" "))
#define PERF_SUBQUERY(x) kPerformance _perf_query_(_T(__FILE__) _T(":") PERF_XSTR(__LINE__) _T(" ") _T(x))
#endif
#else
#define PERF_QUERY
#define PERF_SUBQUERY(x)
#endif

class kPerformance;

#include "kcommon.h"

class kPerformance {
private:
	static std::unordered_map<const tchar*, uint64_t> _timings;
	static uint64_t _baseTime;
	uint64_t _startTime;
	const tchar* _name;

	static uint64_t getTime();
public:
	inline kPerformance(const tchar* name) {
		_name = name;
		_startTime = getTime();
		if (!_baseTime)
			_baseTime = _startTime;
	}
	inline ~kPerformance() {
		uint64_t endTime = getTime();
		_timings[_name] += endTime - _startTime;
	}
	static void save(const std::tstring& filename = _T("perf.txt"));
};
